package com.example.myapplication.framework;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.Toast;

import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {
    private Context mContext;
    private Disposable mDisposable;
    private final int SUCCESS_CODE = 0;

    public BaseObserver(Context context) {
        mContext = context;
    }

    @Override
    public void onSubscribe(Disposable d) {
        mDisposable = d;
    }

    @Override
    public void onNext(BaseEntity<T> value) {
        if (value.getCode() == SUCCESS_CODE) {
            T t = value.getData();
            onHandleSuccess(t);
        } else {
            onHandleError(value.getCode(), value.getMessage());
        }
    }

    @Override
    public void onError(Throwable e) {
//        Log.d("gesanri", "error:" + e.toString());
//
//        Toast.makeText(mContext, "网络异常，请稍后再试111", Toast.LENGTH_LONG).show();
        if(e instanceof HttpException) {
            // Cast e to HttpException and do what you need to
            Log.e("http", "onError: ", e);
        } else {
            // This is another exception, like invalid JSON, etc.
            Log.e("tagggg", "onError: ", e);
        }
    }

    @Override
    public void onComplete() {
        Log.d("gesanri", "onComplete");
    }

    abstract void onHandleSuccess(T t);

    void onHandleError(int code, String message) {
        Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
    }
}
